<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\model\ProductCart;
use app\common\model\ProductCate;
use app\common\model\ProductSpec;
use app\common\tool\Result;
use think\facade\Cache;
use think\Response;
use app\common\model\Product as ProductModel;

class Product extends Base
{
    public function cateList($pid = 0): Response
    {
        return Result::success('success', ProductCate::getCate($pid));
    }

    public function index(): Response
    {
        $param = $this->request->get();
        $map = [];
        foreach ($param as $key => $value) {
            if (!in_array($key, ['type', 'keyword', 'filed', 'sort', 'page', 'limit']) && $value) {
                $map[$key] = $value;
            }
        }
        $like = [];
        if (!empty($param['keyword'])) {
            $like['field'] = 'title';
            $like['keyword'] = trim($param['keyword']);
        }
        if (!empty($param['filed']) && !empty($param['sort'])) {
            $sort[] = ['key' => $param['filed'], 'value' => $param['sort']];
        }
        $sort[] = ['key' => 'sort', 'value' => 'desc'];

        return Result::fastReturn(ProductModel::getPageList($map, 'id,title,price,vip_price,icon,virtual_sales+sales as sales,stock',
            $this->getPage(), $this->getLimit(), true, [], [], $sort, $like));
    }

    public function info($id): Response
    {
        $info = ProductModel::where(['id' => $id, 'status' => 1])
            ->field('id,cate_1,cate_2,title,describe,price,vip_price,spec_open,spec,icon,images,content,virtual_sales+sales as sales,stock')->find();
        if (!$info) return Result::fail('商品不存在或已下架');
        $info->content = handleRichText($info->content);
        $info->images = $info->images ? explode(',', $info->images) : '';
        $info->specInfo = $info->spec ? json_decode($info->spec, true) : '';
        unset($info->spec);
        $this->verifyToken();
        if ($this->user) {
            $cart_num = ProductCart::where(['uid' => $this->user->id])->sum('num');
        } else {
            $cart_num = 0;
        }
        $info->cart_num = $cart_num;
        $info->customer = $this->system['customer'];
        $info->contact = $this->system['contact'];

        return Result::success('success', $info);
    }

    public function getSpecInfo($pid, $spec): Response
    {
        $specValue = ProductSpec::withoutField('delete_time')
            ->where(['pid' => $pid, 'merge_title' => $spec])->find();
        if (empty($specValue)) {
            return Result::fail('当前规格已下架！');
        }
        $specValue->icon = $specValue->icon ?: $specValue->product->icon;
        unset($specValue->product);

        return Result::success('success', $specValue);
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $param['type'] = 1;

        return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
    }
}